define(['config', 'text!app/module/system/dictmanage.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function(config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {
	var grid_url="/api/dict/getDictItemlist";
    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");
    console.log(token);
	var model = avalon.define({
		$id:'dict',
		query:{itemName:"",dictCode:"",memo:"",itemCode:""},
		dictList:[],
		info:[],
		dictInfo:{id:"",dictInfo:""},
		init: function() {
				model.loadMenu();
	            model.loadGrid();
	        	model.addEvent();
	        	
	    },
	  //加载菜单列表
	    loadDictList:function(dictCode){
	    	$(".menu").find(".menuColor").removeClass("menuColor");
	    	$(this).addClass("menuColor");
	    	//点击菜单的适合赋空搜索条件
	    	model.query.dictCode=dictCode;
	    	model.dictInfo.dictCode=dictCode;
	    	model.query.itemName="";
	    	model.query.memo="";
	    	model.query.itemCode="";
	    	model.loadInfo();
	    },
	    loadMenu:function(){
	    	//页面一开始加载 数据字典菜单 
            $.ajax({
                type: "POST",
                url: "/api/dict/getdictlist",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-AuthToken", token);
                },
                success: function(data, status, xhr) {
                	model.dictList=data;
                },
                error: function(responseData, textStatus, errorThrown) {
                    alert("Failed: " + responseData);
                }

            });
	    	
	    },
	    loadGrid:function(){
	    	 var i = Public.setGrid();
	    	 function t(val, opt, row) {
                 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
                 return html_con;
             }
	    	   $("#grid").jqGrid({
	    		   loadBeforeSend: function(jqXHR) {
						jqXHR.setRequestHeader("X-AuthToken", token);
					},
				  	url : grid_url,
			        datatype : "json",	
			        postData: model.query,
				        colModel:[
				        	{name:"operating", label: "操作",  width: '5%', formatter: t, align: "center", title: false },
				        	{name:'id',label: "id",width:'15%', align:"center",title: false,hidden : true},
				        	{name:'itemName',label: "元数据名称",width:'15%', align:"center",title: false},
				        	{name:'standardCode',label: "客户编码",width:'15%',align:'center',title: false},
				            {name:'itemCode',label: "海关编码", width:'15%',align:"center",title: false},
				            {name:'dictCode',label: "字典code",width:'7%',align:'center',title: false},
				            {name:'itemOrder',label: "排序", width:'20%', align:"center",title: false},
				            {name:'memo',label: "备注",width:'10%',align:"center",title: false},
				            {name:'grade',label: "等级",width:'10%',align:"center",title: false},
				            
				        ], 
				        cmTemplate: {
		                    sortable: false,
		                    title: false
		                },
			        page: 1,
			        rowNum : 30,
			        rowList : [ 10, 20, 30 ],
			        height : i.h,
			        autowidth: true,
			        pager : '#page',
			        sortname : 'id',
			        viewrecords : true,
	                forceFit: false,
	                rownumbers:true,
	                multiselect: true,
	                multiboxonly: true, 
			        sortorder : "desc",
			        jsonReader:{
			            root: "data.list",
			            records: "data.totalRow",
	                    total: "data.totalPage",
	                    repeatitems: false,
	                    id: "id"
			        }
	    	   })//jqGrid End
	       },//grid End
	       searchInfo:function(){
	    	   //搜索
	    	   model.loadInfo();
				
			},//search function End
		    edit: function(dictInfo) {
		            if (dictInfo === -1) { // 创建用户
		                model.dictInfo.itemName =""; 
		                model.dictInfo.standardCode ="";
		                model.dictInfo.itemCode ="";
		                model.dictInfo.itemOrder ="";
		                model.dictInfo.memo ="";
		                url = "/api/dict/newDictItem";
		            } else { // 修改用户
		                model.dictInfo = dictInfo;
		                url = "/api/dict/updDictItem";
		            }
		            if(typeof(model.dictInfo.dictCode)!="undefined"){
		            	 // 弹出层
			            dialog({
			                title: '编辑用户信息',
			                content: $('#editUser'),
			                okValue: "确定",
			                ok: function() {
			                    // 提交修改||!isNaN(model.dictInfo.itemOrder)
			                	if(model.dictInfo.itemName==null || model.dictInfo.itemName==""){
			                		alert("元数据名称不能为空")
			                	}else if(isNaN(model.dictInfo.itemOrder)){
			                		alert("排序必须为数字")
			                	}else{
			                		 $.ajax({
					                        type: "POST",
					                        url: url,
					                        data: model.dictInfo,
					                        beforeSend: function(xhr) {
					                            xhr.setRequestHeader("X-AuthToken", token);
					                        },
					                        success: function(data, status, xhr) {
					                        	model.loadInfo();
					                            avalon.log(data);
					                        },
					                        error: function(responseData, textStatus, errorThrown) {
					                            alert("Failed: " + responseData);
					                        }

					                    });
			                		
			                	}
			                   
			                },
			                cancelValue: "取消",
			                cancel: function() {}
			            }).showModal();
		            }
		           
		        },
		        del: function(ids) {
		            dialog({
		                title: "确认操作",
		                content: "确定删除？ 此操作不可恢复！",
		                okValue: "确定",
		                ok: function() {

		                    $.ajax({
		                        type: "POST",
		                        url: "/api/dict/delelDictItem",
		                        data: {
		                            "ids": ids
		                        },
		                        beforeSend: function(xhr) {
		                            xhr.setRequestHeader("X-AuthToken", token);
		                        },
		                        success: function(data, status, xhr) {
		                            if (data) {
		                                $('#grid').jqGrid('delRowData', ids);
		                            //    model.loadInfo();
		                            }
		                        },
		                        error: function(responseData, textStatus, errorThrown) {
		                            alert("Failed: " + responseData);
		                        }

		                    });

		                },
		                cancelValue: "取消",
		                cancel: function() {}
		            }).showModal();
		        },
			reset:function(){
				//重置报关单号
				model.query.itemName="";
				model.query.memo="";
				model.query.itemCode="";
				model.loadInfo();
				
			},//reset function End 
	        addEvent: function() {
	            var t = this;
	            $(".grid-wrap").on("click", ".fa-edit", function(e) {
	                var t = $(this).parent().data("id");
	                avalon.log($("#grid").getRowData(t))
	                model.edit($("#grid").getRowData(t));
	            });
	            // 删除
	            $(".grid-wrap").on("click", ".fa-trash-o", function(t) {
	                var ei = [];
	                var e = $(this).parent().data("id");
	                ei.push(e);
	                model.del(e);
	            });
	            $("#search").click(function(e) {
	                e.preventDefault();
	                model.searchInfo();
	            });
	            $(".fa-refresh").click(function(e) {
	                e.preventDefault();
	                model.reset();
	                model.searchInfo();
	            })
	            $("#add").click(function(t) {
	                model.edit(-1);
	            });
	            $("#btn-batchDel").click(function(e) {
	                e.preventDefault();
	                // if (Business.verifyRight("BU_DELETE")) {
	                var t = $("#grid").jqGrid("getGridParam", "selarrrow");
	                t.length ? model.del(t.join()) : parent.Public.tips({
	                        type: 2,
	                        content: "请选择需要删除的项"
	                    })
	                    // }
	            });
	            // 设置用户角色
	        },
			loadInfo:function(){
				//重新加载数据
				 $("#grid").jqGrid("setGridParam", {
		                url: grid_url,
		                datatype: "json",
		                type: 'POST',
		                postData: model.query.$model
		            }).trigger("reloadGrid");
				
			}//loadModel function End
	})
	
	
	
// 定义视图模块
	  // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function() {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function() {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});